#!/bin/sh
#
# Copyright (C) 2017-2018, 2020  Etersoft
# Copyright (C) 2017-2018, 2020  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

__get_icons_hicolor_list()
{
    local i j
    for i in apps scalable symbolic 8x8 14x14 16x16 20x20 22x22 24x24 28x28 32x32 36x36 42x42 45x45 48x48 64 64x64 72x72 96x96 128x128 144x144 160x160 192x192 256x256 256x256@2x 480x480 512 512x512 1024x1024 ; do
        echo "/usr/share/icons/hicolor/$i"
        for j in actions animations apps categories devices emblems emotes filesystems intl mimetypes places status stock ; do
            echo "/usr/share/icons/hicolor/$i/$j"
        done
    done
}

# args: pkgname buildroot spec
__fix_spec()
{
    local pkgname="$1"
    local buildroot="$2"
    local spec="$3"
    local i

    # drop forbidded paths
    # https://bugzilla.altlinux.org/show_bug.cgi?id=38842
    for i in / /etc /etc/init.d /etc/systemd /bin /opt /usr /usr/bin /usr/lib /usr/lib64 /usr/share /usr/share/doc /var /var/log /var/run \
            /etc/cron.daily /usr/share/icons/usr/share/pixmaps /usr/share/man /usr/share/man/man1 /usr/share/appdata /usr/share/applications /usr/share/menu \
            /usr/share/icons/hicolor $(__get_icons_hicolor_list) ; do
        sed -i \
            -e "s|/\./|/|" \
            -e "s|^%dir[[:space:]]\"$i/*\"$||" \
            -e "s|^%dir[[:space:]]$i/*$||" \
            -e "s|^\"$i/*\"$||" \
            -e "s|^$i/*$||" \
            $spec
    done

    # commented out: conflicts with already installed package
    # drop %dir for existed system dirs
    #for i in $(grep '^%dir "' $spec | sed -e 's|^%dir  *"\(.*\)".*|\1|' ) ; do #"
    #    echo "$i" | grep -q '^/opt/' && continue
    #    [ -d "$i" ] && [ -n "$verbose" ] && echo "drop dir $i from packing, it exists in the system"
    #done

    # replace dir "/path/dir" -> %dir /path/dir
    grep '^"/' $spec | sed -e 's|^"\(/.*\)"$|\1|' | while read i ; do
        # add dir as %dir in the filelist
        if [ -d "$buildroot$i" ] ; then
            subst "s|^\(\"$i\"\)$|%dir \1|" $spec
        #else
        #    subst 's|^\("'$i'"\)$|\1|' $spec
        fi
    done

}

has_repack_script()
{
    local repackcode="$EPM_REPACK_SCRIPTS_DIR/$1.sh"
    [ -s "$repackcode" ]
}

# args: pkgname buildroot spec
__apply_fix_code()
{
    local repackcode="$EPM_REPACK_SCRIPTS_DIR/$1.sh"
    [ -s "$repackcode" ] || return
    [ -f "$repackcode.rpmnew" ] && warning "There is .rpmnew file(s) in $EPM_REPACK_SCRIPTS_DIR dir. The pack script can be outdated."

    shift
    [ "$PROGDIR" = "/usr/bin" ] && SCPATH="$PATH" || SCPATH="$PROGDIR:$PATH"
    local bashopt=''
    [ -n "$debug" ] && bashopt='-x'
    ( unset EPMCURDIR ; export PATH=$SCPATH ; docmd $CMDSHELL $bashopt $repackcode "$1" "$2" "$3" "$4" "$5" ) || fatal "There is an error from $repackcode script"
}

__create_rpmmacros()
{
    cat <<EOF >$HOME/.rpmmacros
%_topdir    $HOME/RPM
%_tmppath    $TMPDIR

%packager    EPM <support@eepm.ru>
%_vendor    EEPM
%_gpg_name    support@etersoft.ru
# TODO: use special user for repack (instead of root of local user)
%_allow_root_build    1
EOF
    remove_on_exit "$HOME/.rpmmacros"
}

# will set RPMBUILD
__try_install_eepm_rpmbuild()
{
    RPMBUILD=/usr/bin/rpmbuild
    [ -x "$RPMBUILD" ] && return

    RPMBUILD=/usr/bin/eepm-rpmbuild
    if [ ! -x $RPMBUILD ] ; then
        epm install eepm-rpm-build
    fi

    if [ -x $RPMBUILD ] ; then
        warning "will use eepm-rpmbuild for rpm packing"
        export EPM_RPMBUILD=$RPMBUILD
        return
    fi

    RPMBUILD=/usr/bin/rpmbuild
}

# will fill repacked_pkgs var
__epm_repack_to_rpm()
{
    local pkgs="$*"

    # Note: install epm-repack for static (package based) dependencies
    assure_exists alien || fatal

    # will set RPMBUILD
    __try_install_eepm_rpmbuild

    if [ ! -x $RPMBUILD ] ; then
        RPMBUILD=/usr/bin/rpmbuild
        # TODO: check for all systems
        case $PKGFORMAT in
            rpm)
                assure_exists $RPMBUILD rpm-build || fatal
                ;;
            deb)
                assure_exists $RPMBUILD rpm || fatal
                ;;
        esac
    fi

    umask 022

    # TODO: improve
    if echo "$pkgs" | grep -q "\.deb" ; then
        assure_exists dpkg || fatal
        # TODO: Для установки требует: /usr/share/debconf/confmodule но пакет не может быть установлен
        # assure_exists debconf
    fi

    local pkg
    local alpkg
    local abspkg
    local tmpbuilddir
    repacked_pkgs=''
    for pkg in $pkgs ; do
        # TODO: keep home?
        HOME="$(mktemp -d --tmpdir=$BIGTMPDIR)" || fatal
        remove_on_exit $HOME
        export HOME
        __create_rpmmacros

        tmpbuilddir=$HOME/$(basename $pkg).tmpdir
        mkdir $tmpbuilddir
        abspkg="$(realpath $pkg)"
        info ""
        info "Repacking $abspkg to local rpm format (inside $tmpbuilddir) ..."

        alpkg=$(basename $pkg)
        # don't use abs package path: copy package to temp dir and use there
        cp -l $verbose $pkg $tmpbuilddir/../$alpkg || cp $verbose $pkg $tmpbuilddir/../$alpkg || fatal

        cd $tmpbuilddir/../ || fatal
        # fill alpkg and SUBGENERIC
        __prepare_source_package "$(realpath $alpkg)"
        cd $tmpbuilddir/ || fatal

        if [ -n "$verbose" ] ; then
            docmd alien --generate --to-rpm $verbose $scripts "../$alpkg" || fatal
        else
            showcmd alien --generate --to-rpm $scripts "../$alpkg"
            a='' alien --generate --to-rpm $scripts "../$alpkg" >/dev/null || fatal
        fi

        # remove all empty dirs (hack against broken dpkg with LF in the end of line) (hack for linux_pantum.deb)
        rmdir * 2>/dev/null

        local subdir="$(echo *)"
        [ -d "$subdir" ] || fatal "can't find subdir in $(pwd)"

        local buildroot="$tmpbuilddir/$subdir"

        # for tarballs fix permissions (ideally fix in pack.d/generic-tar.sh, but there is tar repacking only)
        [ "$SUBGENERIC" = "tar" ] && chmod $verbose -R a+rX $buildroot/*

        # detect spec and move to prev dir
        local spec="$(echo $buildroot/*.spec)"
        [ -s "$spec" ] || fatal "Can't find spec $spec"
        mv $spec $tmpbuilddir || fatal
        spec="$tmpbuilddir/$(basename "$spec")"

        local pkgname="$(grep "^Name: " $spec | sed -e "s|Name: ||g" | head -n1)"

        # run generic scripts and repack script for the pkg
        cd $buildroot || fatal

        __fix_spec $pkgname $buildroot $spec
        __apply_fix_code "generic" $buildroot $spec $pkgname $abspkg $SUBGENERIC
        __apply_fix_code "generic-$SUBGENERIC" $buildroot $spec $pkgname $abspkg
        __apply_fix_code $pkgname $buildroot $spec $pkgname $abspkg
        if ! has_repack_script $pkgname ; then
            __apply_fix_code "generic-default" $buildroot $spec $pkgname $abspkg
        fi
        cd - >/dev/null

        TARGETARCH=$(epm print info -a | sed -e 's|^x86$|i586|')

        showcmd $RPMBUILD --buildroot $buildroot --target $TARGETARCH -bb $spec
        if [ -n "$verbose" ] ; then
            a='' $RPMBUILD --buildroot $buildroot --target $TARGETARCH -bb $spec || fatal
        else
            a='' $RPMBUILD --buildroot $buildroot --target $TARGETARCH -bb $spec >/dev/null || fatal
        fi

        # remove copy of source binary package (don't mix with generated)
        rm -f $tmpbuilddir/../$alpkg
        local repacked_rpm="$(realpath $tmpbuilddir/../*.rpm)"
        if [ -s "$repacked_rpm" ] ; then
            remove_on_exit "$repacked_rpm"
            [ -n "$repacked_pkgs" ] && repacked_pkgs="$repacked_pkgs $repacked_rpm" || repacked_pkgs="$repacked_rpm"
        else
            warning "Can't find converted rpm for source binary package '$pkg' (got $repacked_rpm)"
        fi
        cd $EPMCURDIR >/dev/null
    done

    true
}

